package com.learn.core.controller.learn;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.JwtUtil;
import com.learn.common.utils.PageResult;
import com.learn.common.utils.ResultUtil;
import com.learn.common.utils.StringUtils;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.*;
import com.learn.core.domain.view.CourseTarget;
import com.learn.core.domain.view.UserDetailsGather;
import com.learn.core.dto.*;
import com.learn.core.service.*;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Description
 *
 * @author zhaohongyu
 * @ClassName ExamController
 * @date 2021.04.08 16:33
 * @describe 课程中心
 */
@Api("课程中心")
@RestController
@RequestMapping("/learn/course")
public class CourseController extends WebController<LTheme> {
    @Autowired
    private ILThemeService iLThemeService;
    @Autowired
    private ILCourseService ilCourseService;
    @Autowired
    private ILEnrollService ilEnrollService;
    @Autowired
    private ILChapterService ilChapterService;
    @Autowired
    private ILTeacherService ilTeacherService;
    @Autowired
    private ILOrganizationService ilOrganizationService;
    @Autowired
    private ILEvaluateService ilEvaluateService;
    @Autowired
    private ILCoursewareService ilCoursewareService;
    @Autowired
    private IUserDetailsGatherService iUserDetailsGatherService;
    @Autowired
    private ILGroupingUserService ilGroupingUserService;
    @Autowired
    private ICourseTargetService iCourseTargetService;
    @Autowired
    private ILCourseSortService ilCourseSortService;

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //列表
    @ApiOperation(value = "主题树")
    @PostMapping("/treeTheme")
    public CommonResult<Object> treeTheme(){
        try {
            List<LTheme> lThemes = iLThemeService.queryLThemeAll();
            if(lThemes.size()>0)
                return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,lThemes);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    //专题列表
    @ApiOperation(value = "专题列表")
    @UserLoginToken
    @PostMapping("/courseTheme")
    public CommonResult<Object> courseTheme(HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            // 用户信息
            UserDetailsGather userDetailsGather = userInfo(userId);
            // 用户分组
            List userGroup = userGroup(userId);

            List<Map<String,Object>> list = new ArrayList<>();
            QueryWrapper<LTheme> queryWrapper = new QueryWrapper<LTheme>();
            queryWrapper.eq("parent_node",0);
            List<LTheme> lThemeList = iLThemeService.list(queryWrapper);
            for (LTheme lTheme : lThemeList) {
                Map<String,Object> map = new HashMap<>();
                QueryWrapper<CourseTarget> lCourseQueryWrapper = new QueryWrapper<CourseTarget>();
                lCourseQueryWrapper.eq("course_theme",lTheme.getThemeId());
                lCourseQueryWrapper.eq("course_type","2");
                lCourseQueryWrapper.eq("release_stutes","1");
                if(userGroup.size() > 0){
                    queryWrapper.and(i -> i.eq("course_target_type","0").eq("course_target", userDetailsGather.getOrganizationId())
                            .or(a -> a.eq("course_target_type", "1").in("course_target", userGroup)));
                }else{
                    queryWrapper.and(i -> i.eq("course_target_type","0").eq("course_target", userDetailsGather.getOrganizationId()));
                }
                lCourseQueryWrapper.orderByDesc("release_time");
                lCourseQueryWrapper.last("limit 0,4");
                List<CourseTarget> lCourseList = iCourseTargetService.list(lCourseQueryWrapper);
                map.put("id",lTheme.getThemeId());
                map.put("name",lTheme.getThemeName());
                map.put("data",lCourseList);
                list.add(map);
            }
            return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,list);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //课程排名
    @ApiOperation(value = "课程排名")
    @UserLoginToken
    @GetMapping("/courseRanking")
    public CommonResult<Object> courseRanking(@RequestParam("type")String type){
        try {
            QueryWrapper<LCourse> queryWrapper = new QueryWrapper<LCourse>();
            queryWrapper.eq("course_type",type);
            queryWrapper.groupBy("course_id");
            queryWrapper.orderByDesc("people");
            queryWrapper.last("limit 0,10");
            List<LCourse> lCourses = ilCourseService.list(queryWrapper);
            List<Map<String,Object>> list = new ArrayList<>();
            for (LCourse course : lCourses) {
                Map<String,Object> map = new HashMap<>();
                map.put("id",course.getCourseId());
                map.put("name", course.getCourseName());
                map.put("cover", course.getCourseCover());
                map.put("sortId", course.getCourseSortId());
                LCourseSort lCourseSort = ilCourseSortService.getById(course.getCourseSortId());
                if(null != lCourseSort)
                    map.put("sortName", lCourseSort.getCourseSortName());
                map.put("courseCount",course.getPeople());
                list.add(map);
            }
            return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,list);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //根据主题获取专题列表
    @ApiOperation(value = "根据主题获取专题列表")
    @UserLoginToken
    @PostMapping("/listTheme")
    public PageResult<LCourse> listTheme(@RequestBody LThemeDTO lThemeDTO,HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            // 用户信息
            UserDetailsGather userDetailsGather = userInfo(userId);
            // 用户分组
            List userGroup = userGroup(userId);
            if (lThemeDTO==null||lThemeDTO.getPage()==null||lThemeDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lThemeDTO.getPage(),lThemeDTO.getRows());
            QueryWrapper<CourseTarget> queryWrapper = new QueryWrapper<CourseTarget>();
            if(StringUtils.isNotEmpty(lThemeDTO.getThemeId()))
                queryWrapper.eq("course_theme",lThemeDTO.getThemeId());
            if(StringUtils.isNotEmpty(lThemeDTO.getSearch()))
                queryWrapper.like("course_name",lThemeDTO.getSearch());
            queryWrapper.eq("course_type","2");
            queryWrapper.eq("release_stutes","1");
            queryWrapper.ge("course_fail_time",formatter.format(new Date()));
            if(userGroup.size() > 0){
                queryWrapper.and(i -> i.eq("course_target_type","0").eq("course_target", userDetailsGather.getOrganizationId())
                        .or(a -> a.eq("course_target_type", "1").in("course_target", userGroup)));
            }else{
                queryWrapper.and(i -> i.eq("course_target_type","0").eq("course_target", userDetailsGather.getOrganizationId()));
            }
            queryWrapper.orderByDesc("release_time");
            Page<CourseTarget> lCourses = (Page<CourseTarget>) iCourseTargetService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lCourses)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            // 返回
            return new PageResult(lCourses.getTotal(), lCourses, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //课程详情
    @ApiOperation(value = "课程详情")
    @UserLoginToken
    @GetMapping("/courseInfo")
    public CommonResult<Object> info( @RequestParam("id")String courseId, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if (courseId==null){
                return (CommonResult) ResultUtil.error(ResultEnum.LOAD_ERROR);
            }
            Map<String,Object> map = new HashMap<>();
            LCourse lCourse = ilCourseService.getById(courseId);
            if(null != lCourse){
                map.put("id",lCourse.getCourseId());
                map.put("name",lCourse.getCourseName());
                map.put("courseCover",lCourse.getCourseCover());
                map.put("courseType",lCourse.getCourseType());
                map.put("recommendStutes",lCourse.getRecommendStutes());
                LTeacher lTeacher = ilTeacherService.getById(lCourse.getTeacher());
                if(null != lTeacher){
                    map.put("teacher",lTeacher.getTeacherName());
                }
                LOrganization lOrganization = ilOrganizationService.getById(lCourse.getCourseCompany());
                if(null != lOrganization){
                    map.put("courseCompany",lOrganization.getOrganizationName());
                }
                map.put("classHours",lCourse.getClassHours());
                map.put("description",lCourse.getDescription());
                //评论列表
                //好评数
                QueryWrapper<LEvaluate> evaluateQueryWrapper = new QueryWrapper<>();
                evaluateQueryWrapper.eq("course_id",courseId);
                evaluateQueryWrapper.eq("evaluate_type","1");
                int evaluateCount = ilEvaluateService.count(evaluateQueryWrapper);
                map.put("evaluateCount",evaluateCount);
                map.put("enrollCount",lCourse.getPeople());
                //好评率
                QueryWrapper<LEvaluate> lEvaluateQueryWrapper = new QueryWrapper<>();
                lEvaluateQueryWrapper.eq("course_id",courseId);
                int evaluates = ilEvaluateService.count(lEvaluateQueryWrapper);
                map.put("praise",evaluateCount *100.00 / evaluates);

                // 学习进度
                QueryWrapper<LEnroll> enrollQueryWrapper = new QueryWrapper<>();
                enrollQueryWrapper.eq("course_id",courseId);
                enrollQueryWrapper.eq("user_id",userId);
                LEnroll lEnroll = ilEnrollService.getOne(enrollQueryWrapper);
                if(null != lEnroll){
                    map.put("courseState","1");
                    map.put("courseSpeed",lEnroll.getSpeed());
                }else{
                    map.put("courseState","0");
                }
            }

            // 返回
            return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //课程章节
    @ApiOperation(value = "课程章节")
    @UserLoginToken
    @PostMapping("/courseLChapter")
    public CommonResult<Object> courseLChapter(@RequestBody LChapterDTO lChapterDTO){
        try {
            QueryWrapper<LChapter> queryWrapper = new QueryWrapper<LChapter>();
            queryWrapper.eq("course_id",lChapterDTO.getCourseId());
            queryWrapper.orderByAsc("chapter_seq");
            List<LChapter> lChapters = ilChapterService.list(queryWrapper);
            for (LChapter chapter :lChapters) {
                LCourseware lCourseware = ilCoursewareService.getById(chapter.getCoursewareId());
                chapter.setlCourseware(lCourseware);
            }
            return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,lChapters);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //在线选课
    @ApiOperation(value = "在线选课")
    @UserLoginToken
    @PostMapping("/enroll")
    public CommonResult<Object> enroll(@RequestBody LEnroll lEnroll, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if(null != lEnroll){
                lEnroll.setCreateTime(new Date());
                lEnroll.setCreateUser(userId);
                lEnroll.setUserId(Integer.parseInt(userId));
                lEnroll.setSpeed("0");
                lEnroll.setStutes("0");
                lEnroll.setFinishHours(Double.valueOf(0));
                if(ilEnrollService.save(lEnroll)) {
                    // 增加报名人数
                    Integer courseId = lEnroll.getCourseId();
                    LCourse course = ilCourseService.getById(courseId);
                    int people = course.getPeople();
                    people++;
                    LCourse lCourse = new LCourse();
                    lCourse.setCourseId(courseId);
                    lCourse.setPeople(people);
                    ilCourseService.updateById(lCourse);
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    // 用户详情
    private UserDetailsGather userInfo(String userId){
        QueryWrapper<UserDetailsGather> userDetailsGatherQueryWrapper = new QueryWrapper<UserDetailsGather>();
        userDetailsGatherQueryWrapper.eq("user_id",userId);
        UserDetailsGather userDetailsGather = iUserDetailsGatherService.getOne(userDetailsGatherQueryWrapper);
        return userDetailsGather;
    }

    // 用户分组
    private List userGroup(String userId){
        List groupId = new ArrayList();
        QueryWrapper<LGroupingUser> lGroupingUserQueryWrapper = new QueryWrapper<LGroupingUser>();
        lGroupingUserQueryWrapper.eq("user_id",userId);
        List<LGroupingUser> lGroupingUsers = ilGroupingUserService.list(lGroupingUserQueryWrapper);
        for (LGroupingUser lGroupingUser : lGroupingUsers) {
            groupId.add(lGroupingUser.getGroupingId());
        }
        return groupId;
    }

    //自主选课列表
    @ApiOperation(value = "自主选课列表")
    @PostMapping("/autonomyList")
    public CommonResult<Object> autonomyList(){
        try {
            List<Map<String,Object>> list = new ArrayList<>();
            QueryWrapper<LTheme> queryWrapper = new QueryWrapper<LTheme>();
            queryWrapper.eq("parent_node",0);
            List<LTheme> lThemeList = iLThemeService.list(queryWrapper);
            for (LTheme lTheme : lThemeList) {
                Map<String,Object> map = new HashMap<>();
                QueryWrapper<LCourse> lCourseQueryWrapper = new QueryWrapper<LCourse>();
                lCourseQueryWrapper.eq("course_theme",lTheme.getThemeId());
                lCourseQueryWrapper.eq("course_type","1");
                lCourseQueryWrapper.eq("release_stutes","1");
                lCourseQueryWrapper.eq("recommend_stutes","1");
                lCourseQueryWrapper.orderByDesc("release_time");
                lCourseQueryWrapper.last("limit 0,4");
                List<LCourse> lCourseList = ilCourseService.list(lCourseQueryWrapper);
                map.put("id",lTheme.getThemeId());
                map.put("name",lTheme.getThemeName());
                map.put("data",lCourseList);
                list.add(map);
            }
            return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,list);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //根据主题获取自主选课列表
    @ApiOperation(value = "根据主题获取自主选课列表")
    @PostMapping("/autonomyThemeList")
    public PageResult<LCourse> autonomyThemeList(@RequestBody LThemeDTO lThemeDTO){
        try {
            if (lThemeDTO==null||lThemeDTO.getPage()==null||lThemeDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lThemeDTO.getPage(),lThemeDTO.getRows());
            QueryWrapper<LCourse> queryWrapper = new QueryWrapper<LCourse>();
            if(StringUtils.isNotEmpty(lThemeDTO.getThemeId()))
                queryWrapper.eq("course_theme",lThemeDTO.getThemeId());
            if(StringUtils.isNotEmpty(lThemeDTO.getSearch()))
                queryWrapper.like("course_name",lThemeDTO.getSearch());
            queryWrapper.eq("course_type","1");
            queryWrapper.eq("recommend_stutes","1");
            queryWrapper.eq("release_stutes","1");
            queryWrapper.ge("course_fail_time",formatter.format(new Date()));
            queryWrapper.orderByDesc("release_time");
            Page<LCourse> lCourses = (Page<LCourse>) ilCourseService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lCourses)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            // 返回
            return new PageResult(lCourses.getTotal(), lCourses, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }
}
